import { EventTypeEum, useRegisterEvent } from '@/utils/bus';
import { useRef, useState } from 'react';
import { useRequest } from 'taro-hooks';

export default (
  request: any,
  options?: {
    defaultParams?: any;
    limitSize?: number;
    eventName?: keyof typeof EventTypeEum;
    manual?: boolean;
  }
) => {
  const { limitSize = 10, defaultParams, eventName, manual } = options || {};
  // 分页参数
  const pageQuery = useRef({ current: 1, size: limitSize });
  // 搜索参数
  const searchParams = useRef<any>(defaultParams);
  // 列表数据
  const [data, setData] = useState<any[]>([]);
  // 是否完成加载
  const [finish, setFinish] = useState(false);
  // 条数
  const [total, setTotal] = useState(0);

  // 临时存放数据
  const cacheData = useRef<any[]>([]);
  const { loading, run } = useRequest(request, {
    defaultParams: [{ ...defaultParams, ...pageQuery.current }, false],
    manual: manual,
    onSuccess(res) {
      const { current, size } = pageQuery.current;
      if (current === 1) {
        setData((cacheData.current = res?.records || res || []));
      } else {
        setData(
          (cacheData.current = [...data, ...(res?.records || res || [])])
        );
      }
      setFinish(current * size >= res?.total);
      setTotal(res?.total || 0);
    },
  });

  const reloadRequest = () => {
    return run(
      { ...searchParams.current, ...pageQuery.current },
      searchParams.current !== 1
    );
  };

  // 下一页
  const next = () => {
    if (loading) return;
    pageQuery.current.current++;
    reloadRequest();
  };

  /**
   * @description 条件查询
   */
  const searchBy = (params) => {
    searchParams.current = params;
    pageQuery.current.current = 1;
    setFinish(false);
    setData([]);
    setTotal(0);
    reloadRequest();
  };

  /**
   * @description 重新加载
   */
  const reset = () => {
    pageQuery.current.current = 1;
    setFinish(false);
    setData([]);
    setTotal(0);
    return reloadRequest();
  };
  /**
   * @description 事件订阅 用户不刷新且不发起请求更新页面数据
   */

  useRegisterEvent(eventName, (rowData) => {
    if (rowData) {
      setData(
        (cacheData.current = cacheData.current.map((item) => ({
          ...item,
          ...(item.id === rowData?.id ? rowData : {}),
        })))
      );
    } else {
      reset();
    }
  });

  return {
    scrollProps: {
      data,
      loading,
      total,
      next,
      finish,
      onRefresh: reset,
    },
    searchBy,
    reset,
  };
};
